package com.vr.cloudpicture.controller;

import com.vr.cloudpicture.common.BaseResponse;
import com.vr.cloudpicture.common.ResultUtils;
import com.vr.cloudpicture.exception.ErrorCode;
import com.vr.cloudpicture.exception.ThrowUtils;
import com.vr.cloudpicture.manager.CosManager;
import com.vr.cloudpicture.service.IPictureService;
import com.vr.cloudpicture.service.IUserService;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * 文件控制器
 *
 * @author hzh
 * @date 2025/05/10
 */
@Slf4j
@RestController()
@RequestMapping("/file")
@RequiredArgsConstructor
public class FileController {
    private final CosManager cosManager;
    private final IUserService userService;
    private final IPictureService pictureService;
    @ApiOperation(value = "测试上传文件")
    @PostMapping("/test/upload")
    public BaseResponse<String> testUploadFile(@RequestPart("file") MultipartFile multipartFile) {
        // 文件名
        String filename = multipartFile.getOriginalFilename();
        System.out.println(filename);
        // 文件目录
        String filepath=String.format("/test/%s", filename);
        // 上传文件
        File file=null;
        try {
            // 创建一个临时文件
            file = File.createTempFile(filepath, null);
            // 将要上传的临时文件拷贝到创建的临时文件中
            multipartFile.transferTo(file);
            // 上传
            cosManager.putObject(filepath, file);
        } catch (IOException e) {
            log.error("file upload error,filepath={}", filepath,e);
            ThrowUtils.throwIf(true, ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            // 删除临时文件
            if (file!=null) {
                boolean delete = file.delete();
                if (!delete) {
                    log.error("file delete error,filepath={}", filepath);
                }
            }
        }
        return ResultUtils.success(filepath,"上传成功");
    }

}
